package com.example.grpc.provider.server;

import com.example.grpc.provider.service.HelloServiceImpl;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author liyuncong
 * @version 1.0
 * @file HelloServer
 * @brief HelloServer
 * @details HelloServer
 * @date 2022-11-08
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                        NAME               DESCRIPTION
 * 2022-11-08                  liyuncong          Created
 */
public class HelloServer {

    private static final Logger logger = LoggerFactory.getLogger(HelloServer.class);

    private Server server;

    public void start() throws IOException {
        int port = 50051;

        server = ServerBuilder.forPort(port)
            .addService(new HelloServiceImpl())
            .build()
            .start();

        logger.info("Server started, listening on " + port);

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            logger.error("shutting down gRPC server");
            try {
                HelloServer.this.stop();
            } catch (InterruptedException e) {
                logger.error("shutting down gRPC server error ", e);
            }
        }));
    }

    public void stop() throws InterruptedException {
        if (server != null) {
            server.shutdown().awaitTermination(30, TimeUnit.SECONDS);
        }
    }

    private void blockUntilShutdown() throws InterruptedException {
        if (server != null) {
            server.awaitTermination();
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        final HelloServer helloServer = new HelloServer();
        helloServer.start();
        helloServer.blockUntilShutdown();
    }

}
